﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class AsmLoader : MonoBehaviour
{
    public Text prePath;
    public Button btn;
    // Start is called before the first frame update
    void Start()
    {
        prePath.text = "";
        AddDebug("AsmLoader:");
        AddDebug("persistentDataPath=" + Path.Combine(Application.persistentDataPath));
        var asms = AppDomain.CurrentDomain.GetAssemblies();
        asms = asms.Where((x) => x.FullName.Contains("CommomLogic") || x.FullName.Contains("UILogic")).ToArray();
        for (int i = 0; i < asms.Length; i++)
        {
            AddDebug(asms[i].FullName,true); 
        }
        AddDebug("asms.Length=" + asms.Length,true);
        btn.onClick.AddListener(LoadHot);
        

    }

    void LoadHot()
    {
        string comPath = $"{Application.persistentDataPath}/CommomLogic.dll";
        string tempStr = File.Exists(comPath) ? "comPath存在" : "!!comPath不存在";
        AddDebug("tempStr=" + tempStr);

        try
        {
            AppDomain.CurrentDomain.Load(File.ReadAllBytes(comPath));
        }
        catch (Exception e)
        {
            AddDebug(e.Message);

        }
        try
        {
            Assembly comAsm = Assembly.LoadFile(comPath);
        }
        catch (Exception e)
        {

            AddDebug(e.Message);
        }

        string uiPath = $"{Application.persistentDataPath}/UILogic.dll";

        //AppDomain.CurrentDomain.GetAssemblies().First(x => x.FullName.IndexOf("UILogic") > -1);
        Assembly asm = Assembly.LoadFile(uiPath);
        if (asm != null)
        {
            Type entryType = asm.GetType("zframe.hot.UILogicEntry");
            if (entryType != null)
            {
                var ins = Activator.CreateInstance(entryType);
                MethodInfo methodInfo = entryType.GetMethod("Start");
                if (methodInfo != null)
                {
                    try
                    {
                        methodInfo.Invoke(ins, null);
                    }
                    catch (Exception e)
                    {
                        AddDebug(" methodInfo.Invoke e=" + e.Message);

                    }
                }
            }
        }
    }

    void AddDebug(string msg,bool newLine=false)
    {
        prePath.text = prePath.text + msg+"," + (newLine?"\n":"");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
